module app.grpc.impl.AuthServiceImpl;

import app.grpc.Common;
import app.grpc.AuthService;
import app.grpc.AuthServicerpc;

import app.config.CustomConfig;

import grpc;
import hunt.httpclient;
import hunt.logging.ConsoleLogger;

import std.conv;

/**
 * 
 */
class AuthServiceImpl : AuthServiceBase {

    this() {

    }

    override Status authorize(AuthenticateREQ req, ref AuthenticateRES) {

        LoginMode mode = req.loginMode;
        auto res = new AuthenticateRES();
        try {
            switch (mode) {
            case LoginMode.ACCOUNT:
                dealAccountLogin(req, res);
                break;
            case LoginMode.MOBILE:
                dealMobileLogin(req, res);
                break;
            case LoginMode.TOKEN:
                dealTokenLogin(req, res);
                break;
            default:
                logError("unknown mode %d", mode);
                break;
            }
        } catch (Exception e) {
            res.code = ErrorCode.ERR_DB;
        }

        res.clientId = req.clientId;

        return Status.OK;
    }

    void dealMobileLogin(AuthenticateREQ req, AuthenticateRES res) {
        //string token = AuthorizeByMobile(req.appKey, req.mobile, req.code, res);
        //if (token.length != 0)
        //{
        //  getUserInfo(token, req.appKey, res);
        //  if (res.code == ErrorCode.ERR_NONE)
        //  {
        //    res.authorized = true;
        //    message.MsgDefine.User user = LogInService.processLogin(res.user);
        //    res.user = user;
        //  }
        //}
    }

    void dealAccountLogin(AuthenticateREQ req, AuthenticateRES res) {
        //string token = AuthorizeByAccount(req.appKey,req.username,req.password, res);
        //logInfof("token: %s" ,token);
        //if (token.length != 0)
        //{
        //    getUserInfo(token, req.appKey, res);
        //    if (res.code == ErrorCode.ERR_NONE)
        //    {
        //        res.authorized = true;
        //        message.MsgDefine.User user = LogInService.processLogin(res.user);
        //        res.user = user;
        //    }
        //}
    }

    void dealTokenLogin(AuthenticateREQ req, AuthenticateRES res) {
        getUserInfo(req.accessToken, req.appKey, res);
        if (res.code == ErrorCode.ERR_NONE) {
            // User user = LogInService.processLogin(res.user);
            // res.user = user;
            // LogInService.InitOssInfo(res);
        }
    }

    void getUserInfo(string token, string appKey, AuthenticateRES res) {
        string[string] headers;
        headers["appkey"] = appKey;
        headers["Authorization"] = token;
        auto response = Http.withHeaders(headers).get(serverConfig.uas);
        logInfo("res: %s", response.content);
        res.code = ErrorCode.ERR_REMOTE_RETURN;

        if (response.isOk() && response.json["code"].integer() == 0) {
            logInfof("userId: %s", response.content);
            if (res.user is null) {
                res.user = new User;
            }
            res.user.id = to!string(response.json["data"]["uid"].integer());
            res.user.name = response.json["data"]["nickname"].str();
            res.user.avatar = response.json["data"]["avatar"].str();
            res.user.gender = to!string(response.json["data"]["gender"].integer());
            res.user.birthday = to!string(response.json["data"]["birthday"].integer());
            res.user.mobile = response.json["data"]["mobile"].str();
            res.code = cast(ErrorCode)(response.json["code"].integer());
        }
        if (response.isSuccessful() && response.json["code"].integer() != 0) {
            logInfo("%d", response.json["code"].integer());
            res.code = cast(ErrorCode)(response.json["code"].integer());
            res.user = null;
            logInfo("%d", res.code);
        }
    }

    string AuthorizeByAccount(string appKey, string username, string password, AuthenticateRES res) {
        string[string] headers;
        headers["appkey"] = appKey;
        auto response = Http.withHeaders(headers).post("http://account.openchat.mobi/login/username/password",
                ["username": username, "password": password]);
        string token;
        if (response.isOk() && response.json["code"].integer() == 0) {
            token = response.json["data"]["token"].str();
        }
        if (response.isSuccessful()) {
            res.code = cast(ErrorCode)(response.json["code"].integer());
        } else {
            res.code = ErrorCode.ERR_REMOTE_RETURN;
        }

        return token;
    }

    string AuthorizeByMobile(string appKey, string mobile, string code, AuthenticateRES res) {
        string[string] headers;
        headers["appkey"] = appKey;
        auto response = Http.withHeaders(headers)
            .post("http://account.openchat.mobi/login/mobile/code",
                    ["fullmobile": mobile, "code": code]);
        string token;
        if (response.isOk() && response.json["code"].integer() == 0) {
            token = response.json["data"]["token"].str();
        }
        if (response.isSuccessful()) {
            res.code = cast(ErrorCode)(response.json["code"].integer());
        } else {
            res.code = ErrorCode.ERR_REMOTE_RETURN;
        }
        return token;
    }
}
